﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace SharePointResourcesUpdaterLib
{
    public class ResourcesUpdaterJob : SPJobDefinition
    {
        #region props
        public override string Description
        {
            get
            {
                return Constants.Description;
            }
        }
        public override string DisplayName
        {
            get
            {
                return Constants.JobName;
            }
        }
        public override bool CanRenameOnRestore
        {
            get
            {
                return true;
            }
        }
        public override ulong DiskSizeRequired
        {
            get
            {
                return 0L;
            }
        }
        #endregion
        #region ctors
        /// <summary>
        /// Only for serialization don't use it
        /// </summary>
        public ResourcesUpdaterJob(): base()
        {

        }
        
        private ResourcesUpdaterJob(SPSchedule schedule, bool disabled)
            : base(Constants.UserTriggeredName, new SPWebServiceCollection(SPFarm.Local).First(), null, SPJobLockType.None)
        {
            this.Schedule = schedule;
            this.IsDisabled = disabled;
        }
        #endregion
        public override void Execute(Guid targetInstanceId)
        {
            SPWebServiceCollection svcoll = new SPWebServiceCollection(Farm);
            svcoll.First().ApplyApplicationContentToLocalServer();
            base.Execute(targetInstanceId);
        }
        /// <summary>
        /// Use this constructor to register and trigger a resources update immediatly
        /// </summary>
        public static void UpdateResources()
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                ResourcesUpdaterJob tj = new ResourcesUpdaterJob(new SPOneTimeSchedule(DateTime.Now.AddSeconds(30.0)), false);
                tj.Update();
            });
        }
        /// <summary>
        /// Use this constructor to registrer a recurrent job and/or disabled (so it doesn't run periodically but permits admin to trigger it)
        /// </summary>
        /// <param name="schedule">Whene to run</param>
        /// <param name="disabled">Disabled or not</param>
        public static void UpdateResourcesTrigerredOrPeriod(SPSchedule schedule, bool disabled)
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                ResourcesUpdaterJob tj = new ResourcesUpdaterJob(schedule, disabled);
                tj.Update();
            });
        }
    }
}
